import json
from pyecharts.charts import Map
from pyecharts import options
from pyecharts.options import VisualMapOpts
from pyecharts.options import ToolboxOpts

# 打开文件
data_r = open("F:/Python/res/疫情.txt", "r", encoding="utf-8")
# 读取文件
data = data_r.read()
# 关闭文件
data_r.close()
# 转换成python字典
data = json.loads(data)
# 处理数据
province_data_total = data["areaTree"][0]["children"]
# 取出省份确诊数据
data_list = []
for province in province_data_total:
    province_name = province["name"]
    province_confirm = province["total"]["confirm"]
    data_list.append((province_name, province_confirm))
# print(data_list)
# 创建地图对象
map = Map(init_opts=options.InitOpts(width="1200px", height="600px"))
# 构建地图
map.add("中国疫情地图", data_list, "china")
# 全局选项
map.set_global_opts(
    visualmap_opts=VisualMapOpts(
        is_show=True,
        is_piecewise=True,
        pieces=[
            {"min": 1, "max": 9, "label": "1-9人", "color": "#9bf986"},
            {"min": 10, "max": 99, "label": "1-99人", "color": "#63f443"},
            {"min": 100, "max": 499, "label": "100-499人", "color": "#29c007"},
            {"min": 500, "max": 999, "label": "500-999人", "color": "#f5ef5b"},
            {"min": 1000, "max": 1999, "label": "1000-1999人", "color": "#f7d322"},
            {"min": 2000, "max": 2999, "label": "2000-2999人", "color": "#f7a722"},
            {"min": 3000, "max": 4999, "label": "3000-4999人", "color": "#f78322"},
            {"min": 5000, "max": 9999, "label": "5000-9999人", "color": "#f75322"},
            {"min": 10000, "max": 29999, "label": "10000-29999人", "color": "#c8090e"},
            {"min": 30000, "max": 999999, "label": "30000-99999人", "color": "#58156f"},

        ]
    ),
toolbox_opts = ToolboxOpts(
    is_show=True,  # 是否显示工具箱
    pos_right="80%",  # 位置
    pos_top="10%",
    orient="vertical",
    feature=options.ToolBoxFeatureOpts(
        save_as_image=options.ToolBoxFeatureSaveAsImageOpts(  # 保存为图片
            title="保存为图片",
            pixel_ratio=2
        ),
        restore=options.ToolBoxFeatureRestoreOpts(title="重置"),  # 重置
        magic_type=options.ToolBoxFeatureMagicTypeOpts(  # 动态类型切换
            type_=["line", "bar"]
        )
    )
)
)


# 生成地图
map.render("china_pandemic_confirm.html")
